package com.yinhai.message.implement.dwr.sender;

import com.alibaba.fastjson.JSON;
import com.yinhai.message.api.bean.TMMessage;
import com.yinhai.message.api.bean.TMUser;
import com.yinhai.message.api.vo.TMMessageVo;
import com.yinhai.message.core.sender.IMessageSender;
import com.yinhai.message.core.util.DateFormatUtil;
import com.yinhai.message.implement.websocket.ChatMessageHandler;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yanglq
 *         2018.4.4
 */
@Service
public class WebSocketMessageSender implements IMessageSender<TMMessageVo>{

    @Resource
    private ChatMessageHandler chatMessageHandler;

    @Override
    public List<TMUser> sendMessage(TMMessageVo messageSendVO) {

        TMMessage tmmsg = messageSendVO.getMessage();
        TMUser sendUser = messageSendVO.getUser();

        Map<String, String> msg = new HashMap<>();
        msg.put("mgid", tmmsg.getMgid());
        msg.put("title", tmmsg.getTitle());
        msg.put("content", tmmsg.getContent());
        msg.put("mgdateShow", DateFormatUtil.df2.format(tmmsg.getCreateDate()));
        msg.put("suserid", sendUser.getUserId());
        msg.put("sname", sendUser.getName());
        msg.put("read", "0");
        msg.put("selfType", tmmsg.getSelfType());
		msg.put("otherData1", tmmsg.getOtherData1());
		msg.put("otherData2", tmmsg.getOtherData2());
		msg.put("otherData3", tmmsg.getOtherData3());

        for(TMUser user:messageSendVO.getUserlist() ){
            String str =JSON.toJSONString(msg);
            chatMessageHandler.sendMessageToUser(user.getAppId()+"_"+user.getUserId(), new TextMessage(str));
        }
        return messageSendVO.getUserlist();
    }

}
